extends Node2D

var time
var lives
var score = 0
var current_level
var current_level_number = 0
const GAME_START = "area0"



# class member variables go here, for example:
# var a = 2
# var b = "textvar"
#export (PackagedScene) var Mob
func _ready():
	init_level(current_level_number)
	# Called when the node is added to the scene for the first time.
	# Initialization here
	pass

func _process(_delta):
#	# Called every frame. Delta is time since last frame.
#	# Update game logic here.
	if Input.is_action_pressed("pause"):
		show_game_paused_menu()
		get_tree().paused = true
	pass

func restart_game(start_level_number):
	current_level.do_physics_process = false
	current_level.queue_free()
	current_level_number = start_level_number
	score = 0
	init_level(current_level_number)
	init_game_state()
	get_tree().paused = false
	
func _on_PlayAgainButton_pressed():
	restart_game(1)
	
func next_level():
	current_level.queue_free()
	get_tree().paused = false
	current_level_number += 1
	init_level(current_level_number)

func init_level(level_number):
	init_game_state()
	
	var levelscene = load("res://areas/area" + str(level_number) + ".tscn")
	var level = levelscene.instance()
	current_level = level
	
	add_child(level)
#	init_from_current_level()
	update_HUD()

func _on_GoToNextLevel_pressed():
	next_level()
	
func init_game_state():
	time = 300
	
func update_HUD():
	$HUD/GUI.score = score
	$HUD/GUI.time = time
	$HUD/GUI.lives = lives
	$HUD/GUI.level = current_level_number
	
func on_enemy_was_hit():
#	$enemy_hit_sound.play()
	score += 100
	update_HUD()

const RESUME_GAME = 1
const START_NEW_GAME = 2
const QUIT_GAME = 3
const GO_TO_NEXT_LEVEL = 4
const REPLAY_FROM_CURRENT_LEVEL = 5

func show_game_paused_menu():
	$HUD/VBox/Message.text = "PAUSED"
	$HUD/VBox/Menu.clear()
	$HUD/VBox/Menu.add_item("Resume game", RESUME_GAME)	
	$HUD/VBox/Menu.add_item("Start a new game", START_NEW_GAME)
	$HUD/VBox/Menu.add_item("Quit game", QUIT_GAME)
	$HUD/VBox/Menu.popup()
	$HUD/VBox.show()
	
func show_game_over_menu():
	$HUD/VBox/Message.text = "GAME OVER"
	$HUD/VBox/Menu.clear()
	$HUD/VBox/Menu.add_item("Continue", REPLAY_FROM_CURRENT_LEVEL)
	$HUD/VBox/Menu.add_item("Retry", START_NEW_GAME)
	$HUD/VBox/Menu.add_item("Quit", QUIT_GAME)
	$HUD/VBox/Menu.popup()
	$HUD/VBox.show()

func _on_Menu_id_pressed( ID ):
	if ID == RESUME_GAME:
		get_tree().paused = false
		hide_menu()
	elif ID == QUIT_GAME:
		get_tree().quit()
	elif ID == START_NEW_GAME:
		restart_game(1)
		hide_menu()
	elif ID == REPLAY_FROM_CURRENT_LEVEL:
		restart_game(current_level_number)
		hide_menu()
		
func hide_menu():
		$HUD/VBox/Menu.hide()
		$HUD/VBox.hide()
